//
//  FKShoppingCartVC.m
//  HappyTest
//
//  Created by Macbook Pro on 2019/2/18.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKShoppingCartVC.h"
#import "FKShoppingCartCell.h"
#import "FKConfirmOrderVC.h"
static NSString *const headerId = @"header";

@interface FKShoppingCartVC ()<UITableViewDataSource, UITableViewDelegate, FKShoppingCartCellDelegate>

@property (nonatomic, weak) UIButton *rightItem;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, weak) UIButton *checkBtn;
@property (nonatomic, weak) UIButton *commitBtn;
@property (nonatomic, weak) UILabel *countLabel;
@property (nonatomic, strong) NSArray *selectedIds;
@property (nonatomic, weak) UIView *bottomView;

@property (nonatomic, strong) NSArray *list;
@property (nonatomic, assign) BOOL hasHeXiaoGoods; // 是否有核销商品
@property (nonatomic, assign) BOOL hasNormalGoods; // 是否有物流商品

@end

@implementation FKShoppingCartVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}


- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, 200)];
        
        UIView *container = [[UIView alloc] init];
        [_emptyView addSubview:container];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Whiteshoppingcart"]];
        [container addSubview:imageView];
        
        UILabel *label = [UILabel fk_labelWithFont:fk_adjustFont(16) textColor:fkColor999999 textAlignment:NSTextAlignmentCenter text:@"亲，您的购物车还没有宝贝哦~"];
        [container addSubview:label];
        
        UIButton *bottomBtn = [UIButton fk_btnWithTarget:self action:@selector(bottomBtnClicked) font:fk_adjustFont(15) normalTitle:@"去逛逛" normalTitleColor:fkMainColor selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage imageNamed:@"bg_white"] selectedBgImg:nil];
        [container addSubview:bottomBtn];
        [bottomBtn fk_viewCornerRadius:fk_adjustW(20) borderWidth:0.8 borderColor:fkMainColor];
        
        CGFloat imageW = imageView.image.size.width;
        CGFloat imageH = imageView.image.size.height;
        CGFloat imageX = (fkScreenW - imageW) * 0.5;
        imageView.frame = CGRectMake(imageX, 0, imageW, imageH);
        CGFloat titleH = [label.text sizeWithAttributes:@{NSFontAttributeName : label.font}].height;
        label.frame = CGRectMake(0, imageView.fk_bottom + 20, fkScreenW, titleH);
        CGFloat bottomW = fk_adjustW(225);
        CGFloat bottomH = fk_adjustW(40);
        CGFloat bottomX = (fkScreenW - bottomW) * 0.5;
        bottomBtn.frame = CGRectMake(bottomX, label.fk_bottom + 50, bottomW, bottomH);
        
        __block CGFloat containerH = bottomBtn.fk_bottom;
        [container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.offset(0);
            make.width.mas_equalTo(fkScreenW);
            make.height.mas_equalTo(containerH);
        }];
    }
    return _emptyView;
}

- (void)bottomBtnClicked
{
    self.tabBarController.selectedIndex = 1;
    [self.navigationController popToRootViewControllerAnimated:false];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"refreshCartList" object:nil];
    
    UIButton *rightItem = [UIButton fk_btnWithTarget:self action:@selector(rightItemClicked:) font:fk_adjustFont(14) normalTitle:@"编辑" normalTitleColor:fkColor333333 selectedTitle:@"完成" selectedTitleColor:fkMainColor normalImg:nil selectedImg:nil bgImg:nil selectedBgImg:nil];
    self.rightItem = rightItem;
    rightItem.frame = CGRectMake(0, 0, 50, 44);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    rightItem.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 12);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItem];
    
    // 底部view
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor whiteColor];
    
    UIButton *checkBtn = [UIButton fk_btnWithTarget:self action:@selector(checkBtnClicked:) font:fk_adjustFont(14) normalTitle:@"全选" normalTitleColor:fkColor333333 selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"bank_icon_select_n"] selectedImg:[UIImage imageNamed:@"bank_icon_select_s"] bgImg:nil selectedBgImg:nil];
    [bottomView addSubview:checkBtn];
    self.checkBtn = checkBtn;
    checkBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
    checkBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    UIButton *commitBtn = [UIButton fk_btnWithTarget:self action:@selector(commitBtnClicked) font:fk_adjustFont(17) normalTitle:@"去结算(0)" normalTitleColor:[UIColor whiteColor] selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:[UIImage imageNamed:@"bg_main"] selectedBgImg:nil];
    [bottomView addSubview:commitBtn];
    self.commitBtn = commitBtn;
    
    UILabel *countLabel = [UILabel fk_labelWithFont:fk_adjustFont(15) textColor:fkPriceRed textAlignment:NSTextAlignmentRight text:@"合计: ￥0.00"];
    [bottomView addSubview:countLabel];
    self.countLabel = countLabel;
    countLabel.attributedText = [countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(15)];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_equalTo(fk_adjustW(45));
        make.bottom.offset(fk_adjustW(45));
    }];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    __block CGFloat checkBtnW = checkBtn.imageView.image.size.width + 10 + [checkBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : checkBtn.titleLabel.font}].width;
    [checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.top.bottom.offset(0);
        make.width.mas_equalTo(checkBtnW);
    }];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.offset(0);
        make.width.mas_equalTo(fk_adjustW(120));
    }];
    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(commitBtn.mas_left).offset(-10);
        make.left.equalTo(checkBtn.mas_right).offset(10);
        make.centerY.equalTo(commitBtn);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self loadData];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)rightItemClicked:(UIButton *)btn
{
    btn.selected = !btn.isSelected;
    if (btn.isSelected) {
        [self.commitBtn setTitle:fkFORMAT(@"删除(%zd)", self.selectedIds.count) forState:UIControlStateNormal];
        self.countLabel.hidden = true;
    } else {
        [self.commitBtn setTitle:fkFORMAT(@"去结算(%zd)", self.selectedIds.count) forState:UIControlStateNormal];
        self.countLabel.hidden = false;
    }
}

- (void)checkBtnClicked:(UIButton *)btn
{
    btn.selected = !btn.isSelected;
    
    
    [self getNumAndPrice:true];
}

- (void)commitBtnClicked
{
    if (self.selectedIds.count == 0) {
        [SVProgressHUD showInfoWithStatus:@"请选择需要操作的商品"];
        return;
    }
    if (self.rightItem.isSelected) { // 删除
        fkWeakSelf(self);
        [self fk_alertWithTitle:@"确定要删除选中的商品吗？" confirm:^{
            [weakself delShopingCart:[weakself.selectedIds componentsJoinedByString:@","]];
        }];
    } else { // 结算
        if (self.hasHeXiaoGoods && self.hasNormalGoods) {
            [SVProgressHUD showInfoWithStatus:@"物流商品和核销商品不可以同时下单"];
            return;
        }
        
        [self buyNow:self.selectedIds];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableDictionary *group = self.datas[section];
    NSArray *items = group[@"items"];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKShoppingCartCell *cell = [FKShoppingCartCell cellWith:tableView];
    NSMutableDictionary *group = self.datas[indexPath.section];
    NSArray *items = group[@"items"];
    NSMutableDictionary *item = items[indexPath.row];
    cell.data = item[@"data"];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return fk_adjustW(134);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSMutableDictionary *group = self.datas[section];
    return group[@"headerH"] ? [group[@"headerH"] floatValue] : 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    NSMutableDictionary *group = self.datas[section];
    return group[@"footerH"] ? [group[@"footerH"] floatValue] : 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSMutableDictionary *group = self.datas[section];
    if (group[@"invalid"]) {
        UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
        if (!header) {
            header = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerId];
            UILabel *titleLabel = [UILabel fk_labelWithFont:fk_adjustFont(14) textColor:fkColor333333];
            [header.contentView addSubview:titleLabel];
            titleLabel.tag = 6;
            
            UIButton *clearBtn = [UIButton fk_btnWithTarget:self action:@selector(clearBtnClicked) font:fk_adjustFont(14) normalTitle:@"清空失效商品" normalTitleColor:fkMainColor selectedTitle:nil selectedTitleColor:nil normalImg:nil selectedImg:nil bgImg:nil selectedBgImg:nil];
            
            [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(12);
                make.centerY.offset(0);
            }];
            [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.offset(-12);
                make.top.bottom.offset(0);
            }];
        }
        UILabel *titleLabel = [header viewWithTag:6];
        NSArray *items = group[@"items"];
        titleLabel.text = fkFORMAT(@"失效商品%zd件", items.count);
        return header;
    }
    return nil;
}

// 点击清空失效商品
- (void)clearBtnClicked
{
    
}

#pragma mark - FKShoppingCartCellDelegate
- (void)shoppingCartCell:(FKShoppingCartCell *)cell didClickedCheckBtn:(UIButton *)btn
{
    [self getNumAndPrice:false];
    
    self.checkBtn.selected = (self.datas.count > 0 && self.datas.count == self.selectedIds.count);
}

- (void)shoppingCartCell:(FKShoppingCartCell *)cell updateNum:(NSInteger)num type:(NSString *)type
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSInteger oldNum = [cell.data[@"nums"] integerValue];
    int operaNum = abs((int)num - (int)oldNum);
    param[@"cart_num"] = @(operaNum);
    param[@"cart_id"] = cell.data[@"id"];
    param[@"type"] = type;
    [FKHttpTool postWithSuffix:@"m=Home&c=Cart&a=updateNum" param:param success:^(FKBaseResult *result) {
        [self loadData];
    } failure:nil];
}

- (void)getNumAndPrice:(BOOL)isClickedCheckBtn
{
    double price = 0;
    NSMutableArray *ids = [NSMutableArray array];
    BOOL hasHeXiaoGoods = false;
    BOOL hasNormalGoods = false;
    for (NSMutableDictionary *group in self.datas) {
        for (NSMutableDictionary *item in group[@"items"]) {
            NSMutableDictionary *data = item[@"data"];
            if (isClickedCheckBtn) {
                data[@"selected"] = @(self.checkBtn.isSelected);
            }
            if ([data[@"selected"] boolValue]) {
                [ids addObject:data[@"id"]];
                price += ([data[@"price"] doubleValue] * [data[@"nums"] integerValue]);
                if ([data[@"item_type"] isEqualToString:@"1"]) hasHeXiaoGoods = true;
                if ([data[@"item_type"] isEqualToString:@"2"]) hasNormalGoods = true;
            }
        }
    }
    self.hasHeXiaoGoods = hasHeXiaoGoods;
    self.hasNormalGoods = hasNormalGoods;
    self.selectedIds = ids;
    [self.tableView reloadData];
     
    NSString *title = fkFORMAT(@"%@(%zd)", self.rightItem.isSelected ? @"删除" : @"去结算", self.selectedIds.count);
    [self.commitBtn setTitle:title forState:UIControlStateNormal];
    self.countLabel.text = fkFORMAT(@"合计: ￥%.2f", price);
    self.countLabel.attributedText = [self.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(15)];
}

- (void)loadData
{
    [FKHttpTool postWithSuffix:@"m=Home&c=Cart&a=cartList" param:nil success:^(FKBaseResult *result) {
        [self.tableView.mj_header endRefreshing];
        if (result.isSuccess) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCartNum" object:nil userInfo:@{@"cartNum" : fkFORMAT(@"%@", result.data[@"cart_num"])}];
            NSArray *list = result.data[@"list"];
            self.list = list;
            NSArray *invalidList = result.data[@"list1"];
            
            NSMutableArray *datas = [NSMutableArray array];
            if (list.count > 0) {
                for (NSInteger index = 0; index < list.count; index++) {
                    NSMutableDictionary *group = [NSMutableDictionary dictionary];
                    [datas addObject:group];
                    group[@"footerH"] = @(10);
                    if (index == 0) group[@"headerH"] = @(10);
                    NSMutableDictionary *item = [NSMutableDictionary dictionary];
                    group[@"items"] = @[item];
                    item[@"data"] = [NSMutableDictionary dictionaryWithDictionary:list[index]];
                }
                
            }
            [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.offset(list.count > 0 ? 0 : fk_adjustW(45));
            }];
            
            if (invalidList.count > 0) {
                NSMutableDictionary *group = [NSMutableDictionary dictionary];
                [datas addObject:group];
                group[@"headerH"] = @(fk_adjustW(50));
                group[@"invalid"] = @(true);
                NSMutableArray *items = [NSMutableArray array];
                for (NSInteger index = 0; index < list.count; index++) {
                    NSMutableDictionary *item = [NSMutableDictionary dictionary];
                    [items addObject:item];
                    item[@"data"] = [NSMutableDictionary dictionaryWithDictionary:list[index]];
                }
                group[@"items"] = items;
            }
            
            self.datas = datas;
            self.rightItem.hidden = self.datas.count == 0;
            [self.tableView reloadData];
            
            // 重置相关状态
            self.rightItem.selected = false;
            self.checkBtn.selected = false;
            [self.commitBtn setTitle:@"去结算(0)" forState:UIControlStateNormal];
            self.countLabel.text = @"合计: ￥0.00";
            self.countLabel.attributedText = [self.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(15)];
        }
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    }];
}

- (void)delShopingCart:(NSString *)ids
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"cart_id"] = ids;
    [FKHttpTool postWithSuffix:@"m=Home&c=Cart&a=deleteCart" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [self loadData];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCartNum" object:nil userInfo:@{@"cartNum" : result.data[@"car_num"]}];
//            [self rightItemClicked:self.rightItem];
//            self.checkBtn.selected = false;
//            [self.commitBtn setTitle:@"去结算(0)" forState:UIControlStateNormal];
//            self.countLabel.text = @"合计: ￥0.00";
//            self.countLabel.attributedText = [self.countLabel.text fk_addAttributeStyle:@"合计:" color:fkColor333333 font:fk_adjustFont(15)];
        }
    } failure:nil];
}

// 立即购买
- (void)buyNow:(NSArray *)cartIds
{
    [SVProgressHUD show];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"cart_ids"] = cartIds;
    [FKHttpTool postWithSuffix:@"m=Home&c=Orders&a=create" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD dismiss];
            FKConfirmOrderVC *vc = [[FKConfirmOrderVC alloc] init];
            vc.confirmDict = result.data;
            vc.cartIds = cartIds;
            fkPushNav(vc);
        }
    } failure:nil];
}


@end
